package tron

import (
	"encoding/hex"
	"fisherman/common/crypte/aes"
	"fisherman/common/event"
	"fisherman/common/http"
	"fisherman/main/cfg"
	"fisherman/main/db"
	"fmt"
	"github.com/btcsuite/btcd/btcec"
	"github.com/btcsuite/btcutil/base58"
	"github.com/fbsobreira/gotron-sdk/pkg/address"
	"github.com/fbsobreira/gotron-sdk/pkg/keys"
	"github.com/tidwall/gjson"
	"strings"
)

const USDTContractAddr = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"            // USDT合约地址
const USDTContractAddrHex = "41a614f803b6fd780986a42c78ec9c7f77e6ded13c" // USDT合约地址Hex形式

func IsValidAddress(address string) bool {
	if len(address) != 34 {
		return false
	}
	if !strings.HasPrefix(address, "T") {
		return false
	}
	base58Chars := "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
	for _, char := range address {
		if !strings.ContainsRune(base58Chars, char) {
			return false
		}
	}
	return true
}

// 生成地址
func GenerateAddress() (addr string, privKey string) {
	priv, err := btcec.NewPrivateKey(btcec.S256())
	if err != nil {
		return "", ""
	}
	privBytes := priv.D.Bytes()
	if len(privBytes) != 32 {
		for {
			priv, err = btcec.NewPrivateKey(btcec.S256())
			if err != nil {
				continue
			}
			privBytes = priv.D.Bytes()
			if len(privBytes) == 32 {
				break
			}
		}
	}
	addr = address.PubkeyToAddress(priv.ToECDSA().PublicKey).String()
	privKey = hex.EncodeToString(privBytes)
	return
}

// 检查如果是助记词自动转私钥
func CheckMnemonicOrKey(keyOrMnemonic string) (privateKey string) {
	if !strings.Contains(keyOrMnemonic, " ") && len(keyOrMnemonic) == 64 {
		privateKey = keyOrMnemonic
		return
	}
	private, _ := keys.FromMnemonicSeedAndPassphrase(keyOrMnemonic, "", 0)
	pk_bytes := private.Serialize()
	privateKey = hex.EncodeToString(pk_bytes)
	return
}

// 查询地址是否已激活
func QueryActived(address string) (isActived bool) {
	rsp := http.PostJsonD(cfg.GetAPI()+"/wallet/getaccount", map[string]any{"address": address, "visible": true})
	if rsp == "" {
		return
	}
	account := gjson.Parse(rsp).Map()
	if len(account) > 0 {
		isActived = true
	}
	return
}

func CheckNewAddrBalanceByFromAddrOrId(idOrAddr any) (toAddrNew string, uBalance, tBalance float64) {
	row := db.GetAddress(idOrAddr)
	if row == nil {
		return
	}
	toAddrNew = row["to_addr_new"].(string)
	if toAddrNew == "" {
		return
	}
	uBalance = QueryUSDTBalance(toAddrNew)
	tBalance = QueryTRXBalance(toAddrNew)
	return
}

func GetBackBalance(toAddrNew string, uBalance, tBalance float64) (err string) {
	if len(db.Cfg_pocket_addr) != 34 {
		err = "GetBackBalance() 零钱地址未配置"
		return
	}
	if uBalance > 0 || tBalance > 0 {
		addrKey := db.GetToAddressNewKeyByToAddrNew(toAddrNew)
		//取回U
		if uBalance > 0 {
			_, l, suc := TransferUSDT(toAddrNew, aes.DecryptString(addrKey, cfg.Config.AESKey), db.Cfg_pocket_addr, uBalance, 0, 0)
			if !suc {
				err = fmt.Sprintf("%s\n取回U失败：%s %f", l, toAddrNew, uBalance)
				return
			} else {
				event.Emit(event.Ev_SendMsg2Tg, fmt.Sprintf("%s\n取回U成功：%s %f", l, toAddrNew, uBalance))
			}
		}
		//取回T
		if tBalance > 0 {
			_, _, l, suc := TransferTRX(toAddrNew, aes.DecryptString(addrKey, cfg.Config.AESKey), db.Cfg_pocket_addr, tBalance)
			if !suc {
				err = fmt.Sprintf("%s\n取回T失败：%s %f", l, toAddrNew, tBalance)
				return
			} else {
				event.Emit(event.Ev_SendMsg2Tg, fmt.Sprintf("%s\n取回T成功：%s %", l, toAddrNew, tBalance))
			}
		}
	}
	return
}

func Base58ToHex42(address string) string {
	decoded := base58.Decode(address)
	addressBytes := decoded[1:21]
	return "41" + hex.EncodeToString(addressBytes)
}

func Hex42ToBase58(addressHex string) string {
	return address.HexToAddress(addressHex).String()
}
